package rpcsupport

import (
	"log"
	"net"
	"net/rpc"
	"net/rpc/jsonrpc"
)

// 开启rpc服务器
func ServeRpc(address string, rcvr any) error {
	rpc.Register(rcvr) //注册rpc服务处理的结构体(使用的所有方法)
	listener, err := net.Listen("tcp", address)
	if err != nil {
		return err
	}
	log.Printf("Listening on %s", address)
	defer listener.Close()
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("accept error: %v", err)
			continue
		}
		go jsonrpc.ServeConn(conn) //异步rpc处理
	}
}

// 创建rpc客户端
func NewClient(address string) (client *rpc.Client, err error) {
	conn, err := net.Dial("tcp", address)
	if err != nil {
		return nil, err
	}
	// defer conn.Close() //连接不能关闭，报错
	client = jsonrpc.NewClient(conn)
	return client, nil
}
